window.debug = true;
var m,mw=800,mh=600;
function rMap (w,h,i){
	w=w||mw;
	h=h||mh;
	i=i||0.55;
	var b = 20,
		m = new Map(w,h,b);
	w = Math.ceil(w/b);
	h = Math.ceil(h/b);
	for (var j=w;j--;){
		for (var k=h;k--;){
			var t = m.getNode(j,k).type = Math.round(Math.random()*i);
		}
	}
	return m;
}
function drawMap(m){
	var t = +new Date;
	if (window.debug)console.log(t);
	m = m || window.m;
	var map=document.getElementById('map'),
		c = map.getContext('2d'),
		b = m.blockSize,
		mm= m.map;
	map.width = map.style.width = m.w;
	map.height= map.style.height= m.h;
	c.strokeStyle = '#fff';
	c.clearRect(0,0,mw,mh);
	var start = m.starts[Math.floor(Math.random()*m.starts.length)] || m.starts[0],
		end = m.ends[Math.floor(Math.random()*m.ends.length)] || m.ends[0],
		p = m.makePath(start,end),
		tps = m.types,
		mapSprites = m.spriteMap;
	if (mapSprites.loaded !== true){
		mapSprites = null;
	}
	if (window.debug)console.log(+new Date, new Date-t);
	for (var i in mm){
		var n = mm[i],
			typ = tps[n.type],
			fill = typ.color;
		if (window.debug){
			if (n == start){
				fill = '#0f0';
			}else if (n == end){
				fill = '#f00';
			}else if (p.indexOf(n) > -1){
				fill = '#00f';
			}else if (n.visited){
				fill = '#ddd';
			}
		}
		if (fill){
			c.fillStyle = fill;
			c.fillRect(n.x*b,n.y*b,b,b);
		}
		if (mapSprites && typ.sprite){
			var s = typ.sprite;
			try {
			c.drawImage(mapSprites, s.x, s.y, s.w||b, s.h||b, n.x*b, n.y*b, b, b);
			}catch(err){}
		}
	}
	if (window.debug)console.log(+new Date, new Date-t);
}
function gotMap(e,m){
	window.m = m;
	drawMap(m);
}
function redraw(e){
	drawMap(window.m);
}
window.onload = function(){
	if (window.debug) console.log(+new Date);
	$("body").bind('MapLoaded',gotMap);
	$('button').bind('click',redraw);
	m = window.m = Maps.load('level1');
	if (m)
		drawMap(m);
}